package cn.huiyunche.bms.web.controller;

import cn.huiyunche.bms.backend.service.AccountService;
import cn.huiyunche.bms.base.model.Account;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;



/**
 * Created by zhaoguixin on 2017/7/13.
 */

@Controller
@RequestMapping("/signin")
public class SigninController {

    @Autowired
    private AccountService accountService;

    @RequestMapping()
    public String signin() throws Exception{
        return "signin";
    }

    @RequestMapping("/login")
    public String login(RedirectAttributes attr, @RequestParam("username") String username, @RequestParam("password") String password, @RequestParam(value="rememberMe",required=false) boolean rememberMe) throws Exception{
        String error = null;

        Account account = accountService.getAccountByCode(username);

        if(null == account){
            error ="用户不存在";
            return redirectSignin(attr,error);
        }

        if(!account.getPassword().equals(password)){
            error = "密码错误";
            return redirectSignin(attr,error);
        }

        UsernamePasswordToken token = new UsernamePasswordToken(username,password);
        Subject subject = SecurityUtils.getSubject();
        if(rememberMe){
            token.setRememberMe(true);
        }

        try{
            subject.login(token);
            Session session = subject.getSession();
            session.setAttribute("username",account.getName());
            session.setAttribute("usercode",account.getCode());
            session.setAttribute("usercomment",account.getComment());
            return "redirect:/index";
        }catch (Exception e){
            error="登陆失败"+e.getMessage();
            return redirectSignin(attr,error);
        }
    }

    private String redirectSignin(RedirectAttributes attr,String message){
        attr.addFlashAttribute("message",message);
        return "redirect:/signin";
    }


}
